<?php

class Light_Layout
{
    /**
     * @var Light_View
     */
    public $view;

	/**
	 * Layout name
	 *
	 * @var string
	 */
	protected $_layoutName = 'default';

	/**
	 * @param Light_View $view
	 */
	public function __construct(Light_View $view = null)
	{
	    $this->setView($view);
	}

	/**
     * @return the $view
     */
    public function getView ()
    {
        return $this->view;
    }

	/**
     * @param Light_View $view
     */
    public function setView ($view)
    {
        $this->view = $view;
    }

	/**
	 * @return the $_layoutName
	 */
	public function getLayoutName ()
	{
		return $this->_layoutName;
	}

	/**
	 * @param string $_layoutName
	 */
	public function setLayoutName ($_layoutName)
	{
		$this->_layoutName = $_layoutName;

		return $this;
	}

    /**
     * @param string $layoutName
     * @throws Light_Exception
     * @return string
     */
    public function render($layoutName = null)
    {
        $lookedTemplate = $layoutName !== null ? $layoutName : $this->getLayoutName();

        $file = LIGHT_APPLICATION_PATH . '/layouts/' . (Light_Core::$isAdmin ? 'admin/' : '') . $lookedTemplate . '.phtml';

        if (!is_readable($file)) {
            throw new Light_Exception('Layout not found: ' . $file, 404);
        }

        if (isset($this->errors) && !empty($this->errors)) {
            foreach ($this->errors as $key => $value) {
                $this->errors[$key] = $this->translate($value);
            }
        }

        ob_start();
        require $file;
        return ob_get_clean();
    }

    /**
     * @param string $name
     * @param array $args
     * @return mixed
     */
    public function __call($name, $args)
    {
        return $this->view->__call($name, $args);
    }
}